package coletaDados;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;

public class Largura extends Busca {

	private RegexUtils regex = new RegexUtils();
	private Map<String, List<String>> listStatus = new HashMap<String, List<String>>();
	private boolean failed = true;

	public Largura(Twitter t, int maxProfiles, int qntPag, DBStatus db) {
		super(t, maxProfiles, qntPag, db);
	}

	@Override
	public void executarBuscaPorReferenciados(User usuarioInicial) {
		inicializarBusca();
		proximos.add(usuarioInicial);
		while (!proximos.isEmpty()) {
			usuarioInicial = proximos.remove(0);
			List<String> status = bancoDeStatus.salvarStatus(usuarioInicial,
					qntPaginas);
			listStatus.put(usuarioInicial.getScreenName(), status);
			encontrarProximosPorReferenciados(status);
		}
		(new ConvertGrafemaFonema(bancoDeStatus.getMapStatus())).ConvertSave();
	}

	@Override
	public void executarBuscaPorAmigos(User usuarioInicial) {
		inicializarBusca();
		jaColetados.add(usuarioInicial.getId());
		proximos.add(usuarioInicial);
		while (!proximos.isEmpty()) {
			usuarioInicial = proximos.remove(0);
			List<String> status = null;
			while (bancoDeStatus.getFailed())
				status = bancoDeStatus.salvarStatus(usuarioInicial, qntPaginas);
			listStatus.put(usuarioInicial.getScreenName(), status);
			failed = true;
			while (failed)
				encontrarProximosPorAmigos(usuarioInicial);
		}
		(new ConvertGrafemaFonema(bancoDeStatus.getMapStatus())).ConvertSave();
	}

	@Override
	public void encontrarProximosPorReferenciados(List<String> status) {
		try {
			for (String msg : status) {
				String referenciou = regex.extrairReferenciado(msg);
				if (countProfiles < maxProfiles && referenciou != null) {
					if (!jaPassou.containsKey(referenciou)) {
						countProfiles++;
						jaPassou.put(referenciou, null);
						proximos.add(twitter.showUser(referenciou));
					}
				}
			}
		} catch (TwitterException e) {
			System.err.println("HTTP error: " + e.getStatusCode());
		}
	}

	@Override
	public void encontrarProximosPorAmigos(User user) {
		try {
			IDs ids = twitter.getFriendsIDs(user.getScreenName());
			for (Integer id : ids.getIDs()) {
				if ((countProfiles < maxProfiles)
						&& (!jaColetados.contains(id))) {
					jaColetados.add(id);
					countProfiles++;
					proximos.add(twitter.showUser(id));
				}
			}
			failed = false;
		} catch (TwitterException e) {
			System.err.println("HTTP error: " + e.getStatusCode());
			System.out.println("Retentando...");
			failed = true;
		}
	}

}
